package role

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"server/database/model"
	"server/tool"
	"strconv"
	"strings"
)

var role model.Role
var rolePermission model.RolePermission

func GetList(ctx *gin.Context) {
	keywords := ctx.Query("keywords")
	page, _ := strconv.Atoi(ctx.Query("page"))
	size, _ := strconv.Atoi(ctx.Query("size"))
	result, err := role.GetList(
		tool.Pagination{
			PageNo:   page,
			PageSize: size,
			KeyWords: keywords,
		})
	if err == nil {
		ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取成功！", "list": result})
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "数据为空！"})
	}
}
func GetOne(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Query("id"))
	result, err := role.GetOne(uint(id))
	if err == nil {
		ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取成功！", "data": result})
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "数据为空！"})
	}
}
func Add(ctx *gin.Context) {
	role = model.Role{}
	role.RoleName = ctx.PostForm("role_name")
	authTree := ctx.PostForm("auth_tree")
	permissions := strings.Split(authTree, ",")
	var authTrees []model.RolePermission
	for _, auth := range permissions {
		authTrees = append(authTrees, model.RolePermission{
			Permission: auth,
		})
	}
	role.Permission = authTrees
	_, err := role.Add(role)
	if err == nil {
		ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "添加成功！"})
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "添加失败"})
	}
}
func Edit(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.PostForm("id"))
	role = model.Role{}
	role.ID = uint(id)
	role.RoleName = ctx.PostForm("role_name")
	authTree := ctx.PostForm("auth_tree")
	permissions := strings.Split(authTree, ",")
	var authTrees []model.RolePermission
	for _, auth := range permissions {
		authTrees = append(authTrees, model.RolePermission{
			Permission: auth,
		})
	}
	role.Permission = authTrees
	err := role.Edit(role)
	if err == nil {
		ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "修改成功！"})
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "修改失败"})
	}
}
func Del(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.PostForm("id"))
	err := role.Del(uint(id))
	if err == nil {
		ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除成功！"})
	} else {
		ctx.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除失败"})
	}
}
